<?php
/**
 * @author  snail
 * @since   2009-11-16
 * @desc   文件上传
 */
class upload{
	/**
	 * @desc 文件上传方法
	 * @param Array $ARG       上传文件的属性
	 */
	public function uploadfile($ARG=array(
	'File'  => array(),
	'Dir'   =>         '')){
		//默认目录
		$dir = "upload/";
		//文件原始名称
		$oldname = $ARG['File']['name'];
		//文件类型
		$tmp = explode('.',$oldname);
		$filetype = $tmp[count($tmp)-1];
		//重命名(文件新名称)
		$newname = rand().time().".".$filetype;
		//上传目录处理
		if(!isset($ARG['Dir']) || $ARG['Dir']==''){
			$dir .= '';
		}else{
			$dir = $ARG['Dir'];
		}
		if(file_exists($dir)){
			$uploaddir = $dir;
		}
		else{
			$uploaddir = $this->setDir("./upload/");
		}
		//上传
		$uploadfile = $uploaddir.$newname;
		//echo $ARG['File']['tmp_name'];
		if(is_uploaded_file($ARG['File']['tmp_name'])){
			if(move_uploaded_file($ARG['File']['tmp_name'],$uploadfile)){
			
			}
			else{
			
			}
		}
		//返回数据，便于操作。
		$File  = array();
		$File['oldname']    =  $oldname;
		$File['newname']  =  $newname;
		$File['uploadfile']  =  $uploadfile;
		return $File;
	}
	/**
	 * @desc 创建目录
	 *
	 * @param String $dir
	 * @param default $mod
	 */
	public function setDir($dir,$mod=0777){
		//路径格式是否正确，以/结束。
		//echo $dir;
		//echo substr($dir,-1);
		if(substr($dir,-1) !='/'){
			$dir .= '/';
		}
		if(!file_exists($dir)){
			$dirs = explode('/',$dir);
			$path =$dirs[0];
			for($i=0;$i<count($dirs);$i++){
				$path .= '/'.$dirs[$i];
				try{
				if(!is_dir($path)){
					if(!mkdir($path,$mod)){
						$error = "不能创建上传目录：".$path;
						throw  new Exception($error);
					}
				  }
				}
				catch (Exception $e){
					echo $e->getMessage();
				}
			}
			if(realpath($path)){
				return $path;
			}
		}
	}
}
?>